import socket
import time

multicast_ip = "239.0.0.1"
multicast_port = 7789

if __name__ == "__main__":
    # udp套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)
    # 允许多播
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
    # 发送组播数据
    count = 0
    id = "/test_liuj"
    try:
        while True:
            msg = f"{id}: 组播信息 {count}"
            sock.sendto(msg.encode("utf-8"), (multicast_ip, multicast_port))
            count += 1
            time.sleep(1)
    except KeyboardInterrupt:
        print("结束")
    finally:
        sock.close()